//
//  BindPhoneNumViewController.m
//  BaseProject
//
//  Created by 王洋 on 2020/10/19.
//  Copyright © 2020 王洋. All rights reserved.
//
#import "UIButton+CountDown.h"
#import "TTUDIDManager.h"
#import "JPUSHService.h"

#import "TT_WebviewController.h"
#import "OpenInstallSDK.h"

#import "BindPhoneNumViewController.h"

@interface BindPhoneNumViewController ()

@property (weak, nonatomic) IBOutlet UITextField *phoneTF;

@property (weak, nonatomic) IBOutlet UITextField *codeTF;

@property (weak, nonatomic) IBOutlet UIButton *handleBtn;

@property (weak, nonatomic) IBOutlet UIButton *countDownBtn;

@property (weak, nonatomic) IBOutlet UILabel *linkText;


@end

@implementation BindPhoneNumViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self initView];
}

- (void)initView {
    
    
    [UIApplication sharedApplication].idleTimerDisabled = YES;
    self.navigationController.navigationBarHidden = YES;
    #if RT_INTERACTIVE_PUSH
        self.rt_navigationController.rt_enableInteractivePush = YES;
    #endif
        
    self.phoneTF.leftView= [[UIView alloc]initWithFrame:CGRectMake(0,0,30,40)];
    self.phoneTF.leftViewMode=UITextFieldViewModeAlways;

    self.codeTF.leftView= [[UIView alloc]initWithFrame:CGRectMake(0,0,30,40)];
    self.codeTF.leftViewMode=UITextFieldViewModeAlways;
    
    self.codeTF.rightView= [[UIView alloc]initWithFrame:CGRectMake(0,0,90,40)];
    self.codeTF.rightViewMode=UITextFieldViewModeAlways;
    
    WEAKSELF
    self.linkText.userInteractionEnabled = YES;
    [self.linkText addGestureTapEventHandle:^(id  _Nonnull sender, UITapGestureRecognizer * _Nonnull gestureRecognizer) {
            
        TT_WebviewController *vc = [[TT_WebviewController alloc] init];
        vc.webUrl = [NSString stringWithFormat:@"%@/%@", BA_GlobalPdf_Domain, kSecretPdf];
        
                
        vc.modalPresentationStyle = UIModalPresentationPopover;
        [weakSelf.navigationController presentViewController:vc animated:YES completion:nil];
        
    }];
    
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    
    WEAKSELF
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [weakSelf.handleBtn pp_clipCorners:UIRectCornerAllCorners radius:weakSelf.handleBtn.frame.size.height/2];
        
        [weakSelf.countDownBtn pp_clipCorners:UIRectCornerAllCorners radius:weakSelf.countDownBtn.frame.size.height/2];
    });
}

#pragma mark 返回按钮
- (IBAction)closeAction:(id)sender {
    
    [self.navigationController dismissViewControllerAnimated:NO completion:nil];
    [[TT_TabbarViewController shareTabbar] setCurrentIndex:TT_TabbarIndexType_Home];
}

- (IBAction)handleAction:(id)sender {
    //绑定成功后登录
    [self request_bingPhone];
}

- (IBAction)codeAction:(id)sender {
    
    [self request_bindPhoneSms];
}

- (void)request_bindPhoneSms {

    if (self.phoneTF.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入手机号"];
        [SVProgressHUD dismissWithDelay:1];
        return;
    }
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:self.phoneTF.text forKey:@"mobile"];
    [dic setValue:@"1" forKey:@"type"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_SMS];

    WEAKSELF
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        [SVProgressHUD dismiss];

        if ([data isKindOfClass:[NSDictionary class]]) {
            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                
                [weakSelf.countDownBtn startWithTime:59
                                           title:@"重新获取"
                                  countDownTitle:@"s"
                                       mainColor:UIColorHex(0xFDB44B)
                                      countColor:UIColorHex(0xFDB44B)];
            } else {
                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"message"]];
                [SVProgressHUD dismissWithDelay:1];
            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {

        [SVProgressHUD showErrorWithStatus:@"请求异常"];
        [SVProgressHUD dismissWithDelay:1];

    }];
}


- (void)request_bingPhone {
    
    if (self.phoneTF.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入手机号"];
        [SVProgressHUD dismissWithDelay:1];
        return;
    }
    
    if (self.codeTF.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入密码"];
        [SVProgressHUD dismissWithDelay:1];
        return;
    }
    
//    NSString *alias = [NSString stringWithFormat:@"%@%@",self.phoneTF.text,[TTUDIDManager getUniqueDeviceID]];
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:self.phoneTF.text forKey:@"username"];
    [dic setValue:[TTUDIDManager getUniqueDeviceID] forKey:@"alias"];
    [dic setValue:[TTUserModel sharedObject].installModel.myCode forKey:@"myCode"];

    if (self.openid.length > 0) {
        [dic setValue:self.openid forKey:@"openid"];
        [dic setValue:@"wx" forKey:@"bindType"];
    }
    
    if (self.aliId.length > 0) {
        [dic setValue:self.aliId forKey:@"aliId"];
        [dic setValue:@"ali" forKey:@"bindType"];
    }

    [dic setValue:self.codeTF.text forKey:@"vcode"];
    [dic setValue:@"2" forKey:@"type"];


    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Platform,API_ThirdLogin];

WEAKSELF
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        [SVProgressHUD dismiss];
        if ([data isKindOfClass:[NSDictionary class]]) {
            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                
                NSDictionary *resultDic = [data valueForKey:@"data"];
                if (![resultDic isKindOfClass:[NSDictionary class]]) {
                    return;
                }
                NSString *token = [resultDic valueForKey:@"token"];
                NSMutableDictionary *user = [resultDic valueForKey:@"user"];
                
                BOOL isRegister = [[resultDic valueForKey:@"isRegister"] boolValue];
                if (isRegister) {
                    [OpenInstallSDK reportRegister];
                    [TTUserModel sharedObject].isRegister = YES;
                }
                
                [[TTUserModel sharedObject].userModelDefault setValue:token forKey:@"TT_token"];
                
                BOOL isNewer = [[resultDic valueForKey:@"isNewer"] boolValue];
                [[TTUserModel sharedObject].userModelDefault setValue:isNewer?@"1":@"0" forKey:@"TT_isNewer"];
                
                [[TTUserModel sharedObject].userModelDefault synchronize];
                [[TTUserModel sharedObject] fillUserModelWithDic:user];
                
                if (weakSelf.completion) {
                    weakSelf.completion(YES, resultDic);
                }
                
                [weakSelf.navigationController dismissViewControllerAnimated:YES completion:nil];

            } else {
                
                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"message"]];
                [SVProgressHUD dismissWithDelay:1];
                
            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        
        [SVProgressHUD showErrorWithStatus:@"请求异常"];
        [SVProgressHUD dismissWithDelay:1];
    }];

}

@end
